package com.gzhu.knowledgeAdmin.parammanage;

import com.gzhu.knowledgeAdmin.common.dto.param.ParamAddRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamDeleteRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamGetRequest;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.repository.VariableTypeRepository;
import com.gzhu.knowledgeAdmin.entity.VariableType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VariableParamCRUD implements ParamCRUD<VariableType>{

    @Autowired
    private VariableTypeRepository variableTypeRepository;

    @Override
    public List<String> getSimpleList() {
        List<VariableType> variableTypeList = variableTypeRepository.findAll();
        return variableTypeList.stream().map(variableType -> variableType.getName()).collect(Collectors.toList());
    }

    @Override
    public Page<VariableType> getList(ParamGetRequest paramGetRequest) {
        VariableType variableType = new VariableType();
        variableType.setName(paramGetRequest.getValue());

        ExampleMatcher matcher = ExampleMatcher.matching()
                //contains 模糊匹配
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<VariableType> example = Example.of(variableType, matcher);

        Pageable pageable = PageRequest.of(paramGetRequest.getPageNum() - 1, paramGetRequest.getPageSize());

        return variableTypeRepository.findAll(example, pageable);
    }

    @Override
    public void addParam(ParamAddRequest paramAddRequest) {
        String value = paramAddRequest.getValue();

        VariableType variableTypeByName = variableTypeRepository.getVariableTypeByName(value);
        if (variableTypeByName != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"对应参数已经存在");
        }

        VariableType variableType = new VariableType();
        variableType.setName(value);
        variableTypeRepository.save(variableType);
    }

    @Override
    public void deleteParam(ParamDeleteRequest paramDeleteRequest) {
        List<Integer> ids = paramDeleteRequest.getIds();

        variableTypeRepository.deleteAllByIdInBatch(ids);
    }
}
